package com.iot.task;

import com.alibaba.fastjson2.JSONObject;
import com.iot.mqtt.MqttHelper;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.List;

/**
 * 模拟设备属性上报任务
 * 每5秒模拟上报一次设备属性数据
 */
@Component
@Slf4j
public class PropertyMockTask {

    private final List<String> mockDevices = List.of("device001", "device002");

    @Scheduled(fixedRate = 5000) // 每5秒执行
    public void mockPropertyUpload() {
        for (String deviceId : mockDevices) {
            JSONObject json = new JSONObject();
            json.put("temperature", 20 + Math.random() * 10);
            json.put("humidity", 50 + Math.random() * 20);
            json.put("timestamp", Instant.now().toString());

            String topic = "device/" + deviceId + "/property";
            try {
                MqttHelper.getInstance().send(topic, json.toString().getBytes(StandardCharsets.UTF_8));
                log.info("模拟属性上报: [{}] -> {}", deviceId, json);
            } catch (Exception e) {
                log.error("模拟上报失败", e);
            }
        }
    }
}
